package cn.itsource.product.controller;



import cn.itsource.product.domain.Product;
import cn.itsource.product.query.ProductQuery;
import cn.itsource.product.service.IProductService;
import cn.itsource.utils.AjaxResult;
import cn.itsource.utils.PageList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController //@Controller +@ResponseBody
@RequestMapping("/product")
//@CrossOrigin//spring 5及以上的版本能用
public class ProductController {

    @Autowired
    private IProductService service;

    @GetMapping
    public List<Product> queryAll(){

        return  service.loadAll();
    }
   //添加和修改
    @PutMapping
    public AjaxResult saveOrUpdate(@RequestBody Product product){
        try {
            service.saveOrUpdate(product);
            return  AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return  AjaxResult.me().setSuccess(false).setMessage(e.getMessage());
        }
    }
     //分页查询
    @PostMapping
    public PageList<Product> queryPage(@RequestBody ProductQuery query){
        PageList<Product> page = service.page(query);
        return  page;

    }
    //删除的
    @DeleteMapping("/{id}")
    public AjaxResult delete(@PathVariable("id") Long id){
        try {
            service.delete(id);
            return  AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return  AjaxResult.me().setSuccess(false).setMessage(e.getMessage());
        }
    }
    //删除的
    @GetMapping("/detail/{id}")
    public Product detail(@PathVariable("id") Long id){
        try {
            return service.detail(id);
        } catch (Exception e) {
            e.printStackTrace();
            return  null;
        }
    }

    @PatchMapping
    public AjaxResult onSale(@RequestBody Long[] ids){//ids [12,13,14]
        try {
           /*
            后台的实现方案
            循环数组，调用删除方法[垃圾实现方案]
           for (Long id : ids) {
                service.delete(id);
            }*/
            service.onSale(ids);

        } catch (Exception e) {
            e.printStackTrace();
            return  AjaxResult.me().setSuccess(false).setMessage(e.getMessage());
        }
        return AjaxResult.me();
    }


}
